package ua.dp.md05;
import ua.dp.md05.dao.ProductDao;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.List;

@Path("/product")
public class ProductRS {
    @Inject
    private ProductDao productDao;

    @Path("/all")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<ProductDTO> getAllProducts() {
        return assembleProductDTOs(productDao.findAll());
    }

    @Path("/page")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<ProductDTO> getProducts(@QueryParam("pagenum") Integer pageNum,
                                        @QueryParam("pagesize") Integer pageSize)
    {
        int firstresult = pageNum * pageSize;
        int maxresults = (pageNum + 1) * pageSize;
        return assembleProductDTOs(productDao.find(maxresults, firstresult));
    }

    @Path("/barcode")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public ProductDTO getProduct(@QueryParam("barcode") String barcode)
    {
        Product product = productDao.findByBarcode(barcode);
        return product == null ? null : assembleProductDTO(product);
    }

    private List<ProductDTO> assembleProductDTOs(List<Product> products)
    {
        List<ProductDTO> productDTOs = new ArrayList<ProductDTO>();
        for (Product product : products)
        {
            productDTOs.add(assembleProductDTO(product));
        }
        return productDTOs;
    }

    private ProductDTO assembleProductDTO(Product product)
    {
        ProductDTO productDTO = new ProductDTO();
        productDTO.setBarcode(product.getBarcode());
        productDTO.setTitle(product.getTitle());
        productDTO.setContent(product.getContent());
        productDTO.setAuthor(product.getAuthor().getUsername());
        productDTO.setCreated(product.getCreated());

        return productDTO;
    }

}